<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Foundation\Auth\User;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Templates;
use App\Models\AdminUser;
use App\Models\Group;
use App\Models\Domain;
use App\Models\Wechat;
use App\Models\CopyWechat;
use App\Models\Originate;

use Log,DB,Cache, Event,Schema;
use App\Events\permChangeEvent;

class IndexController extends Controller
{
    public function index(Request $request)
    {
		if($request->cache=='_ou7i44y7j22d88yr83'){
			Event::fire(new permChangeEvent());
			return redirect('/admin/index')->withSuccess('????ɹ???');
		}
        /*//
         $uid = auth()->user()->id;
        $condition = [['uid', '>', 0],];
        $conditionUser = [['id', '>', 0],];
        if($uid > 1){
            $condition = array('uid'=>$uid);
            $conditionUser = array('id'=>$uid);
        }
        $template = Templates::where('uid',auth()->user()->id)->first();
        if($template === NULL){
            $templateUser = Templates::find(1);
            $newDataTmp['uid'] = auth()->user()->id;
            $newDataTmp['username']= auth()->user()->name;
            $newDataTmp['name'] = $templateUser->name;
            $newDataTmp['mark'] = $templateUser->mark;
            $newDataTmp['source_code'] = $templateUser->source_code;
            Templates::insert($newDataTmp);
        }

        $request->session()->put('authAdminCondition',$condition);
        $request->session()->put('authAdminUserCondition',$conditionUser);
        //Log::warning('warning');
		$uid = auth()->user()->id;
		//??????
		$admin_users = AdminUser:: select('name')->where(function($query) use ($uid){ if($uid!=1){ $query->where('id',$uid);}})->orderBy('id','desc')->get();
		$admin_users = $admin_users->toArray();
		$data['admin_users'] = array_column($admin_users,'name');
		$data['admin_users_count'] = count($data['admin_users'])*90-50;
		
		//ģ?????
		$templates_count = AdminUser::select(DB::raw('count(uid) as c'))->leftJoin('templates','templates.uid','=','admin_users.id')->where(function($query) use ($uid){ if($uid!=1){ $query->where('admin_users.id',$uid);}})->orderBy('admin_users.id','desc')->groupBy('admin_users.id')->get();
		$templates_count = $templates_count->toArray();
		$data['templates_count'] = array_column($templates_count,'c');
		//??????
		$group_count = AdminUser::select(DB::raw('count(uid) as c'))->leftJoin('groups','groups.uid','=','admin_users.id')->where(function($query) use ($uid){ if($uid!=1){ $query->where('admin_users.id',$uid);}})->orderBy('admin_users.id','desc')->groupBy('admin_users.id')->get();
		$group_count = $group_count->toArray();
		$data['group_count'] = array_column($group_count,'c');
		//??ͳ??
		$domain_count = AdminUser::select(DB::raw('count(uid) as c'))->leftJoin('domains','domains.uid','=','admin_users.id')->where(function($query) use ($uid){ if($uid!=1){ $query->where('admin_users.id',$uid);}})->orderBy('admin_users.id','desc')->groupBy('admin_users.id')->get();
		$domain_count = $domain_count->toArray();
		$data['domain_count'] = array_column($domain_count,'c');
		//΢?ͳ??
		$wechat_count = AdminUser::select(DB::raw('count(uid) as c'))->leftJoin('wechats','wechats.uid','=','admin_users.id')->where(function($query) use ($uid){ if($uid!=1){ $query->where('admin_users.id',$uid);}})->orderBy('admin_users.id','desc')->groupBy('admin_users.id')->get();
		$wechat_count = $wechat_count->toArray();
		$data['wechat_count'] = array_column($wechat_count,'c');*/


		$yesterdayTime = date('Y-m-d',time()-86400);
		$todayTime = date('Y-m-d');
		$tomorrowTime = date('Y-m-d',time()+86400);
		//CacheTime minutes
		$cacheMinutes = 600;

		$idsCopy=[];
		$idsOriginate = [];
		if(Cache::has('idsCopy')||Cache::has('idsOriginate')){
			$idsCopy = Cache::get('idsCopy');
			$idsOriginate = Cache::get('idsOriginate');
		}else{
			$todayCopyWechatData = CopyWechat::select('id','ip','channel','keyword','domain','template','created_at')->whereBetween('created_at',[$todayTime,$tomorrowTime])->get();
			$todayOriginateData = Originate::select('id','ip','channel','keyword','channel','keyword','domain','created_at')->whereBetween('created_at',[$todayTime,$tomorrowTime])->get();
			//唯一Copy Ids
			foreach ($todayCopyWechatData->groupBy('ip') as $key => $obj) {
				$idsCopy[] = $obj[0]->id;
			}
			Cache::put('idsCopy',$idsCopy,$cacheMinutes);
			//唯一来源Ids
			foreach ($todayOriginateData->groupBy('ip') as $key => $obj) {
				$idsOriginate[] = $obj[0]->id;
			}
			Cache::put('idsOriginate',$idsOriginate,$cacheMinutes);
		}
		
 	// 	$todayCopyWechatData = Cache::remember('todayCopyWechatData', $cacheMinutes, function() {
		//     return CopyWechat::select('id','ip','channel','keyword','domain','template','created_at')->whereBetween('created_at',[$todayTime,$tomorrowTime])->get();
		// });
		// $todayOriginateData = Cache::remember('todayOriginateData', $cacheMinutes, function() {
		//     return Originate::select('id','ip','channel','keyword','channel','keyword','domain','created_at')->whereBetween('created_at',[$todayTime,$tomorrowTime])->get();
		// });
		


		// ----------Copy----Start
		//all today copy
		$data['today']['cp_count'] = $todayCopyWechatData->count();
		//only today
		$data['today']['cp_only_count'] = $todayCopyWechatData->unique('ip')->count();
		//last five minutes
		$data['today']['cp_last_five_minutes_count'] = $todayCopyWechatData->filter(function($obj){
			return time()-300 < strtotime($obj->created_at);
		})->unique('ip')->count();
		//last hour
		$data['today']['cp_last_hour_count'] = $todayCopyWechatData->filter(function($obj){
			return time()-3600 < strtotime($obj->created_at);
		})->unique('ip')->count();
		//channel && template statistics
		$data['today']['originate_channel_statistics'] = Cache::remember('originate_channel_statistics', $cacheMinutes, function() {
		    return Originate::select(DB::raw('count(*) as count,id, channel'))->whereIn('id',Cache::get('idsOriginate'))->groupBy('channel')->orderBy('count','desc')->get();
		});
		
		$data['today']['cp_template_statistics'] = Cache::remember('cp_template_statistics', $cacheMinutes, function() {
		    return CopyWechat::select(DB::raw('count(*) as count,id, template'))->whereIn('id',Cache::get('idsCopy'))->groupBy('template')->orderBy('count','desc')->get();
		});
		

		$data['today']['cp_domain_statistics'] = Cache::remember('cp_domain_statistics', $cacheMinutes, function() {
		    return CopyWechat::select(DB::raw('count(*) as count,id, domain'))->whereIn('id',Cache::get('idsCopy'))->groupBy('domain')->orderBy('count','desc')->get();
		});
		// ----------Copy----End
		// ----------Originate----Start
		//originate_count
		$data['today']['originate_count'] = $todayOriginateData->count();
		//originate_only_count
		$data['today']['originate_only_count'] = $todayOriginateData->unique('ip')->count();
		
		$data['today']['originate_last_five_minutes_count'] = $todayOriginateData->filter(function($obj){
			return time()-300 < strtotime($obj->created_at);
		})->unique('ip')->count();
		//
		$data['today']['originate_last_hour_count'] = $todayOriginateData->filter(function($obj){
			return time()-3600 < strtotime($obj->created_at);
		})->unique('ip')->count();

		// ----------Originate----End
		$data['today']['cp_channel'] = CopyWechat::select('id','ip','channel','keyword','domain','template','created_at')->whereIn('id',$idsCopy)->orderBy('created_at','desc')->skip(0)->take(10)->get();
		// serach originate
		$data['today']['originate_keyword'] = Originate::select('id','ip','channel','keyword','domain','created_at')->whereIn('id',$idsOriginate)->where('channel','sogou')->orWhere('channel','baidu')->orderBy('created_at','desc')->skip(0)->take(100)->get();
		// besides search originate
		$data['today']['originate_besides_search'] = Originate::select('id','ip','channel','keyword','domain','created_at')->whereIn('id',$idsOriginate)->where('keyword','?')->orWhere('channel','')->orderBy('created_at','desc')->skip(0)->take(10)->get();

		//--Historical keyword comparison
		//Today Keyword
		//$data['today']['originate_today_keyword'] = Originate::select('id','ip','channel','keyword','domain','created_at')->where('channel','sogou')->orWhere('channel','baidu')->orderBy('created_at','desc')->whereBetween('created_at',[$todayTime,$tomorrowTime])->skip(0)->take(20)->get()->unique('ip');
		//$data['today']['originate_historical_keyword'] = Originate::select('id','ip','channel','keyword','domain','created_at')->where('channel','sogou')->orWhere('channel','baidu')->orderBy('created_at','desc')->skip(0)->take(20)->get()->unique('ip');


		$data['today']['originate_today_keyword_lists'] = Originate::select(DB::raw('count(*) as count,keyword'))->whereNotIn('keyword',['无','{keyword}',''])->groupBy('keyword')->orderBy('count','desc')->whereBetween('created_at',[$todayTime,$tomorrowTime])->get();
		$data['today']['originate_today_keyword'] = array();
		foreach ($data['today']['originate_today_keyword_lists'] as $key => $value) {
			if($key < 50){
				$data['today']['originate_today_keyword'][]=$value;
			}else{
				break;
			}

		}
		$data['today']['originate_today_keyword_count']=$data['today']['originate_today_keyword_lists']->count();

		$data['today']['originate_historical_keyword_lists'] = Originate::select(DB::raw('count(*) as count,keyword'))->whereNotIn('keyword',['无','{keyword}',''])->groupBy('keyword')->orderBy('count','desc')->get();
		$data['today']['originate_historical_keyword'] = array();
		foreach ($data['today']['originate_historical_keyword_lists'] as $key => $value) {
			if($key < 50){
				$data['today']['originate_historical_keyword'][]=$value;
			}else{
				break;
			}

		}
		
		$data['today']['originate_historical_keyword_count']=$data['today']['originate_historical_keyword_lists']->count();
        return view('admin.index.index',$data);
    }

}
